import Foundation

@MainActor
class LoginViewModel: ObservableObject {
    @Published var isLoading = false
    @Published var showAlert = false
    @Published var alertMessage = ""
    @Published var isLoggedIn = false
    @Published var codeButtonText = "获取验证码"
    @Published var isCodeButtonEnabled = true
    
    private var apiService = APIService.shared
    private var countdownTimer: Timer?
    private var countdown = 60
    
    // 密码登录
    func login(phone: String, password: String) async {
        guard validatePhone(phone) else { return }
        guard validatePassword(password) else { return }
        
        isLoading = true
        
        let parameters: [String: Any] = [
            "phone": phone,
            "password": password
        ]
        
        do {
            // 使用APIService的公共方法
            let response: APIResponse<LoginResponse> = try await apiService.request(
                endpoint: .login(path: "mobile/password"),
                method: .POST,
                parameters: parameters
            )
            
            isLoading = false
            
            if response.isSuccess {
                // 保存token和过期时间
                if let loginData = response.data {
                    UserDefaults.standard.set(loginData.token, forKey: APIConfig.tokenName)
                    // 设置token过期时间为30天
                    let expirationDate = Date().addingTimeInterval(30 * 24 * 60 * 60)
                    UserDefaults.standard.set(expirationDate, forKey: "tokenExpirationDate")
                }
                // 更新登录状态
                isLoggedIn = true
                // 获取用户信息
                await getUserInfo()
                // 发送登录成功通知
                NotificationCenter.default.post(name: NSNotification.Name("UserDidLogin"), object: nil)
            } else {
                showAlert = true
                alertMessage = response.message ?? "登录失败"
            }
        } catch {
            isLoading = false
            showAlert = true
            alertMessage = error.localizedDescription
        }
    }
    
    // 验证码登录
    func loginWithSmsCode(phone: String, code: String) async {
        guard validatePhone(phone) else { return }
        guard validateCode(code) else { return }
        
        isLoading = true
        
        let parameters: [String: Any] = [
            "phone": phone,
            "captcha": code
        ]
        
        do {
            // 使用APIService的公共方法
            let response: APIResponse<LoginResponse> = try await apiService.request(
                endpoint: .login(path: "mobile/captcha"),
                method: .POST,
                parameters: parameters
            )
            
            isLoading = false
            
            if response.isSuccess {
                // 保存token
                if let loginData = response.data {
                    UserDefaults.standard.set(loginData.token, forKey: APIConfig.tokenName)
                    // 设置token过期时间为30天
                    let expirationDate = Date().addingTimeInterval(30 * 24 * 60 * 60)
                    UserDefaults.standard.set(expirationDate, forKey: "tokenExpirationDate")
                }
                // 更新登录状态
                isLoggedIn = true
                // 获取用户信息
                await getUserInfo()
                // 发送登录成功通知
                NotificationCenter.default.post(name: NSNotification.Name("UserDidLogin"), object: nil)
            } else {
                showAlert = true
                alertMessage = response.message ?? "登录失败"
            }
        } catch {
            isLoading = false
            showAlert = true
            alertMessage = error.localizedDescription
        }
    }
    
    // 注册功能
    func register(phone: String, password: String, confirmPassword: String, code: String) async {
        guard validatePhone(phone) else { return }
        guard validatePassword(password) else { return }
        guard validateCode(code) else { return }
        
        // 确认两次密码输入一致
        guard password == confirmPassword else {
            showAlert = true
            alertMessage = "两次输入的密码不一致"
            return
        }
        
        isLoading = true
        
        let parameters: [String: Any] = [
            "phone": phone,
            "password": password,
            "code": code
        ]
        
        do {
            // 使用APIService的公共方法
            let response: APIResponse<LoginResponse> = try await apiService.request(
                endpoint: .register,
                method: .POST,
                parameters: parameters
            )
            
            isLoading = false
            
            if response.isSuccess {
                // 注册成功后自动登录
                showAlert = true
                alertMessage = "注册成功，请登录"
                // 可以选择自动切换到登录模式
            } else {
                showAlert = true
                alertMessage = response.message ?? "注册失败"
            }
        } catch {
            isLoading = false
            showAlert = true
            alertMessage = error.localizedDescription
        }
    }
    
    // 发送短信验证码
    func sendSmsCode(phone: String) async {
        guard validatePhone(phone) else { return }
        
        isLoading = true
        isCodeButtonEnabled = false
        
        let parameters: [String: Any] = [
            "phone": phone
        ]
        
        do {
            // 使用APIService的公共方法
            let response: APIResponse<BaseResponse> = try await apiService.request(
                endpoint: .sendSmsCode,
                method: .POST,
                parameters: parameters
            )
            
            isLoading = false
            
            if response.isSuccess {
                startCountdown()
            } else {
                showAlert = true
                alertMessage = response.message ?? "发送验证码失败"
                isCodeButtonEnabled = true
            }
        } catch {
            isLoading = false
            showAlert = true
            alertMessage = error.localizedDescription
            isCodeButtonEnabled = true
        }
    }
    
    // 微信登录
    func wechatLogin() {
        // 实现微信登录
        showAlert = true
        alertMessage = "微信登录功能暂未实现"
    }
    
    // 获取用户信息
    private func getUserInfo() async {
        do {
            let response = try await apiService.fetchUserCenterInfo()
            
            if response.isSuccess {
                // 保存用户信息
                if let userInfo = response.data {
                    // 将用户信息保存到UserDefaults
                    if let encoded = try? JSONEncoder().encode(userInfo) {
                        UserDefaults.standard.set(encoded, forKey: "userInfo")
                    }
                    // 通知用户信息更新
                    NotificationCenter.default.post(name: NSNotification.Name("UserInfoUpdated"), object: nil)
                }
            }
        } catch {
            print("获取用户信息失败: \(error.localizedDescription)")
        }
    }
    
    // 验证手机号
    private func validatePhone(_ phone: String) -> Bool {
        if phone.isEmpty {
            showAlert = true
            alertMessage = "请输入手机号"
            return false
        }
        
        if phone.count != 11 {
            showAlert = true
            alertMessage = "请输入正确的手机号"
            return false
        }
        
        return true
    }
    
    // 验证密码
    private func validatePassword(_ password: String) -> Bool {
        if password.isEmpty {
            showAlert = true
            alertMessage = "请输入密码"
            return false
        }
        
        if password.count < 6 {
            showAlert = true
            alertMessage = "密码长度不能小于6位"
            return false
        }
        
        return true
    }
    
    // 验证验证码
    private func validateCode(_ code: String) -> Bool {
        if code.isEmpty {
            showAlert = true
            alertMessage = "请输入验证码"
            return false
        }
        
        if code.count != 6 {
            showAlert = true
            alertMessage = "请输入6位验证码"
            return false
        }
        
        return true
    }
    
    // 开始倒计时
    private func startCountdown() {
        countdown = 60
        updateCodeButtonText()
        
        countdownTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] timer in
            guard let self = self else {
                timer.invalidate()
                return
            }
            
            self.countdown -= 1
            self.updateCodeButtonText()
            
            if self.countdown <= 0 {
                timer.invalidate()
                self.isCodeButtonEnabled = true
                self.codeButtonText = "获取验证码"
            }
        }
    }
    
    private func updateCodeButtonText() {
        codeButtonText = "\(countdown)秒后重试"
    }
    
    deinit {
        countdownTimer?.invalidate()
    }
}
